<?php
/**
 * 自动创建数据库模型
 * User: Administrator
 * Date: 2018\8\31 0031
 * Time: 10:43
 */

namespace app\command;


use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;

class createDbModel extends  Command
{
    protected function configure()
    {

        $this->setName('createDbModel')->setDescription('这个是自动创建表模型程序')
            ->addUsage($this->getName()."说明");
        $this->addOption('tablename', 't', Option::VALUE_OPTIONAL, '表名称',false); //选项值选填
        $this->addOption('alltable', 'a', Option::VALUE_OPTIONAL, 'all重新生成',false); //选项值选填

    }

    protected function execute(Input $input, Output $output)
    {
        $tablename=$input->getOption("tablename");
        $allTable=$input->hasOption("alltable");

        if($tablename&&$allTable){
            $output->error("不能同时输入多个参数");
            return false;
        }
        if($tablename){
            $this->createDbModel($tablename,$output);
        }

        if($allTable){
            foreach ($this->getAllTable() as $tabname) {
                $this->createDbModel($tabname,$output);
            }
        }
    }

    private function getAllTable()
    {
        $list=Db::query("show tables;");
        $tableList=[];
        foreach ($list as $item) {
            foreach ($item as $val) {
                $tableList[]= $val;
            }
        }
        return $tableList;
    }

    /**
     * @param string $tableName
     * @param Output $output
     * @return bool
     */
    private function createDbModel($tableName="", Output $output)
    {
        $database_list=explode(",",config("database.database"));
        $database=isset($database_list[0])?$database_list[0]:$database_list;
        $HAStable=Db::query(
            "select COUNT(1) as num from information_schema.tables where table_name = '".$tableName
            ."' and table_schema = '".$database."';   "
        );
        if($HAStable[0]["num"]<=0){
            $output->warning("表".$tableName."不存在!");
            return false;
        }

        $tableInfo=Db::query(
            "select COLUMN_NAME,COLUMN_COMMENT,DATA_TYPE,COLUMN_DEFAULT from information_schema.COLUMNS where table_name = '".$tableName
            ."' and table_schema = '".$database."';   "
        );

        if(count($tableInfo)<=0){
            return false;
        }

        $tableName=trim($tableName);
        $str = config('database.prefix');
        if(substr($tableName,0,strlen($str)) == $str){
            $tableName= substr($tableName,strlen($str)-1,strlen($tableName));
        }
        else{
            $output->warning("表".$tableName."必须".$str."开头");
            return false;
        }

        for(;strpos($tableName,"_")!==false;){
            $strIndex=strpos($tableName,"_");
            if($strIndex!==false){
                $replacestr=substr($tableName,$strIndex,2);
                $daxie= str_replace("_" ,"",strtoupper($replacestr)  );
                $tableName=str_replace($replacestr,$daxie,$tableName);
            }
        }

        $string="\n";
        foreach ($tableInfo as $column_info) {

            $string.="\n   /*\n".
                "    * [备注信息:".$column_info['COLUMN_COMMENT']."]\n".
                "    * [数据类型:".$column_info['DATA_TYPE']."]\n".
                "    * [默认值:".$column_info['COLUMN_DEFAULT']."]\n".
                "    */\n".
                "   public $" ."_" .$column_info['COLUMN_NAME']." = \"".$column_info['COLUMN_NAME']."\"".";"."\n\n";
        }


        $filecontent='<?php
/**
 * Created by Think cli.
 * Date: ' .date("Y-m-d H:i:s").'
 */
namespace app\Lib\Model\DbModel;

use think\Model;

class '.$tableName.' extends Model
{
'.$string.'
}';

        $filename=APP_PATH."Lib/Model/DbModel/".$tableName.".php";
        $output->info("模块".$tableName."生成成功!");
        $this->wf($filename,$filecontent);
        return true;
    }

    function wf($file="newfile.txt",$content=""){
        $myfile = fopen($file, "w") or die("Unable to open file!");
        fwrite($myfile, $content);
        fclose($myfile);
    }
}